<script lang="ts" setup>
import { ref, onMounted, nextTick, watch } from 'vue'
import type { TreeInstance } from 'element-plus'
import permission from '../../api/permission'

import { usePermissionSelectStore } from '../../store/permissionSelect'
import { useAddRoleStore } from '../../store/addRole'

const addRoleStore = useAddRoleStore()
const permissionSelectStore = usePermissionSelectStore()
const treeRef = ref<TreeInstance>()
const defaultProps = {
    children: 'children',
    label: 'label',
}
// 方法2：事件监听
const handleCheck = (currentNode: any, checkedStatus: any) => {
    addRoleStore.addRole.permission = checkedStatus.checkedKeys;
};
// 设置勾选节点的方法
const setCheckedNodes = () => {
    nextTick(() => {
        if (
            treeRef.value &&
            addRoleStore.addRole?.permission &&
            addRoleStore.addRole.permission.length > 0 &&
            permissionSelectStore.permissionList.length > 0
        ) {
            treeRef.value.setCheckedKeys(addRoleStore.addRole.permission)
        }
    })
}
const setdNodesNull = () => {
    nextTick(() => {
        if (treeRef.value) {
            treeRef.value.setCheckedKeys([])
        }
    })
}
// 监听权限列表变化（假设 permissionSelectStore 是 reactive 对象）
watch(
    () => permissionSelectStore.permissionList,
    (newList) => {
        if (newList.length > 0) {
            setCheckedNodes()
        }
    },
    { immediate: true }
)
watch(
    () => addRoleStore.addRole.permission,
    () => { setCheckedNodes() },
    { immediate: true }
)
watch(
    () => addRoleStore.addRole.id==='',
    () => { setdNodesNull() },
    { immediate: true }
)
onMounted(async () => {
    await permission.getPermissionSelect().then(res => {
        permissionSelectStore.setPermissionList(res.data.data)
    }).catch(err => {
        console.log(err)
    })
})
</script>
<template>
    <!-- 添加多列容器 -->
    <div class="multi-column-tree">
        <el-tree ref="treeRef" style="max-width: 600px" :data="permissionSelectStore.permissionList" show-checkbox
            default-expand-all node-key="id" highlight-current :props="defaultProps" @check="handleCheck" />
    </div>
</template>

<style scoped>
.multi-column-tree {
    column-count: 3;
    /* 分成 3 列 */
    column-gap: 20px;
    /* 列间距 */
}

/* 防止树节点被截断到不同列 */
.multi-column-tree :deep(.el-tree-node) {
    break-inside: avoid;
    /* 关键属性：禁止断开 */
    margin-bottom: 8px;
    /* 可选：增加节点间距 */
}
</style>